package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.parallelandroid.entity.UserInfo;
import com.example.parallelandroid.utils.SPUtils;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PersonalActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView tvName,tvIntroduce,tvGender,tvProvince,tvBirthday;
    private Button btUpdate;
    private ShapeableImageView ivHead;
    private SharedPreferences user;
    private SharedPreferences.Editor editor;
    //Glide请求图片选项配置
    private RequestOptions requestOptions = RequestOptions.circleCropTransform()
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存
    //用于页面跳转时传递数据
    private UserInfo userInfo;
    private SharedPreferences sharedPreferences;

    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);

        // 获取SharedPreferences
        user = getSharedPreferences("user", MODE_PRIVATE);
        userId = user.getString("userId", "userId");

        // 获取控件
        ivHead = findViewById(R.id.iv_headimg);
        btUpdate = findViewById(R.id.btn_updateper);
        tvName = findViewById(R.id.tv_name);
        tvIntroduce = findViewById(R.id.tv_introduce);
        tvGender = findViewById(R.id.tv_gender);
        tvProvince = findViewById(R.id.tv_province);
        tvBirthday = findViewById(R.id.tv_birthday);
        toolbar = findViewById(R.id.personaltoolbar);

        // 为ToolBar添加返回键
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 添加默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); // 设置返回键可用
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //取出缓存
        String imageUrl = SPUtils.getString("imageUrl"+userId,null,this);
        if(imageUrl != null){
            Glide.with(this).load(imageUrl).apply(requestOptions).into(ivHead);
        }

        //获取数据库数据
        getData();
        //点击按钮实现跳转到编辑页面
        btUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent upintent = new Intent(PersonalActivity.this,UpdatePersonActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("userinfo",userInfo);
                upintent.putExtras(bundle);
                startActivity(upintent);
                finish();
            }
        });

    }

    //获取数据库数据
    private void getData() {
        Constant.logger.info("开始从服务端获取用户个人信息数据 userId=" + userId);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"userInfo/findUserInfoByUserId?userId="+userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("从服务端获取用户个人信息数据", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String perdata = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(perdata);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response", e);
                }
                GsonBuilder builder = new GsonBuilder().setDateFormat("yyyy-MM-dd");
                builder.registerTypeAdapter(java.util.Date.class, new JsonDeserializer<Date>() {
                    public java.util.Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                        return new Date(json.getAsJsonPrimitive().getAsLong());
                    }
                });
                Gson gson = builder.create();
                try {
                    userInfo = gson.fromJson(new JSONObject(perdata).getJSONObject("data").toString(),new TypeToken<UserInfo>(){}.getType());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        // 此处执行UI操作
                        tvName.setText(userInfo.getNickName());
                        tvGender.setText(userInfo.getGender());
                        tvIntroduce.setText(userInfo.getBio());
                        tvProvince.setText(userInfo.getProvince());
                        //将用户昵称和省份信息存入全局
                        editor = user.edit();
                        editor.putString("userProvince",userInfo.getProvince());
                        editor.putString("nickName",userInfo.getNickName());
                        editor.putString("userBio",userInfo.getBio());
                        editor.commit();
                        if (userInfo.getBirthday()==null){
                            tvBirthday.setText("无");
                        }else{
                            long date = userInfo.getBirthday().getTime();
                            java.util.Date utilDate = new java.util.Date(date);
                            String nDate = sdf.format(utilDate);
                            tvBirthday.setText(nDate);
                        }
                    }
                });

            }
        });
    }

    public void changeAvatar(View view) {
    }
}